import { cloneDeep,uniqBy } from 'lodash'
import { parse } from 'qs'
import { message } from 'antd'
import { Link, hashHistory } from 'dva/router'
import {
  getLifeServiceCategoryDetail,
  saveLifeServiceCategory,
  updateLifeServiceCategory
} from './lifeServiceCategoryEditServ'

const defultState = {
  actionType: '',
  detail: {},
  images:[],
  query: {
    category: '',
  }
}

const tmpModule = {
  state: cloneDeep(defultState),
  subscriptions: {
    setup ({dispatch, history}) {
      history.listen(({pathname, query}) => {
        if ('' + tmpModule.pathname === '' + pathname) {
          dispatch({ type: 'updateStore', payload: cloneDeep(defultState) });
          // 执行业务操作
          let {id,actionType} = query
          if(id){
            dispatch({type: 'getDetail', payload: {id}}) 
          }
          dispatch({type: 'updateStore', payload: {actionType}})
        }
      })
    }
  },
  
  effects: {    
    * createLifeServiceCategory ({payload}, {put, select, call}) {
        let {detail} = payload
        let {images} = yield select(state => state[tmpModule.namespace])
        if(images.length == 0){
          message.error("图标不能为空")
          return
        }
        console.log("=====================", detail)
        detail.icon = images.length > 0 ? images[0]:""
        console.log("==============xxxx =======", detail)
        let {data, success, msg} = yield call(saveLifeServiceCategory, detail)
        if (success) {
          message.success('操作成功', () => {
              defultState.biz.refreshListDatas(true)
          })
         
        } else {
          message.error(msg)
        }
    },
    * updateLifeServiceCategory ({payload}, {put, select, call}) {
        let {detail} = payload
        let {images} = yield select(state => state[tmpModule.namespace])
        if(images.length == 0){
          message.error("图标不能为空")
          return
        }
        detail.icon = images.length > 0 ? images[0]:""
        let {data, success, msg} = yield call(updateLifeServiceCategory, detail)
        if (success) {
          message.success('更新成功', () => {
              defultState.biz.refreshListDatas(true)
          })
        
        } else {
          message.error(msg)
        }
    },

    * getDetail ({payload}, {put, select, call}) {
      try {
        let {images} = yield select(state => state[tmpModule.namespace])
        let {data, success} = yield call(getLifeServiceCategoryDetail, payload)
        let detail = {}
        if (success) {
          detail = data
          images = [detail.icon]
          yield put({type: 'updateStore', payload: {detail, images}})
        }
      } catch (e) {
        console.error(e)
      }
    },
  },
  
  reducers: {
    updateStore (preState, action) {
      return {...preState, ...action.payload}
    }
  }
}

export default tmpModule
